package com.think.in.spring.ioc.overview.container;

import com.think.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author : zjj
 * @date : 2021/12/28 12:53
 */
@Configuration
public class AnnotationApplicationContextAsIoCContainerDemo {
    public static void main(String[] args) {
        DefaultListableBeanFactory listableBeanFactory = new DefaultListableBeanFactory();

        AnnotationConfigApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext();

        annotationConfigApplicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);
        // 启动容器
        annotationConfigApplicationContext.refresh();


        lookupCollectionByType(annotationConfigApplicationContext);
        lookupCollectionByType(annotationConfigApplicationContext.getBeanFactory());
    }

    /**
     * 通过类型查找 集合
     * @param beanFactory
     */
    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if(beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);

            System.out.println("类型查找 ，集合：" + beansOfType);

        }
    }


    @Bean
    public User user(){
        User user = new User();
        user.setId(1);
        user.setName("小马哥");
        return user;
    }
}
